﻿#! /usr/bin/python
# -*- coding: utf-8 -*-

import codecs
import re
import string
import sys

zf = lambda x, y: string.zfill(str(x), y)

n = '\x0D\x0A'

class lines:
    ''' '''
    def __init__(self , flpath_s, encoding):
        self.flpath_s = flpath_s
        # for list of possible encoding see
        # http://docs.python.org/library/codecs.html#standard-encodings
        #self.sfile_fl = codecs.open(flpath_s, 'r', encoding) 
        #2011-05-04_1634
        self.sfile_fl = codecs.open(flpath_s, 'rb', encoding) 
    def __getitem__( self , index ):
            line_s = self.sfile_fl.readline()
            if line_s:
                return line_s
            else:
                raise IndexError

def main(inpFile, inpEncoding, outEncoding, outFileExt=''):
    ''' '''
    cnt = 0
    #encoding = sys.argv[2]
    #fo = codecs.open(inpFile[:-4] + outFileExt, 'w', outEncoding)
    #2011-05-05_1637
    fname = string.split(inpFile, '\x5C')[-1]
    fname = string.split(fname, '.')[0]

    fo = codecs.open(fname + outFileExt, 'wb', outEncoding)
    #for line in lines('zadanie.txt'):
    print "    Note: Any encoding errors will be listed in file encd-err.out."

    for idx, line in enumerate(lines(inpFile, inpEncoding)):
        cnt += 1

        line = re.sub('\x0D\x0A', '', line)
        # remove single unix/mac end of lines, vp 2010-10-13_1756
        line = re.sub('\x0D', '', line)
        line = re.sub('\x0A', '', line)

        #fo.write(zf(cnt,10)+'^'+line)
        try:
            fo.write(line + n)
        except:
            #pass
            #print str(line)
            ##print str(idx),',',
            ef = open('encd-err.out','a')
            ef.write(line + n)
            ef.close()

    fo.close()

if __name__ == '__main__':
    #main(inpFile='03PredajnaZmluva.csv.datt', inpEncoding='utf-16', outEncoding='utf-8')
    main(     inpFile='KB_KD1.tx2'
            , inpEncoding='cp852'
            , outEncoding='utf-8'
            , outFileExt='_utf8.txt')
    #print 'syntax: app.exe <txt file> <ascii|utf-8|utf-16>'

